package com.synphonecs;

import it.gerdavax.android.bluetooth.BluetoothSocket;
import it.gerdavax.android.bluetooth.LocalBluetoothDevice;
import it.gerdavax.android.bluetooth.RemoteBluetoothDevice;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Formatter;
import java.util.Locale;

import android.content.Context;

public class BluetoothSender {
	protected static final int PORT = 11;
	private RemoteBluetoothDevice remoteBluetoothDevice = null;
	private LocalBluetoothDevice localBluetoothDevice = null;
	private BluetoothSocket socket;
	private OutputStream outputStream;
	
	public BluetoothSender(Context ctx, String address) throws Exception {
		localBluetoothDevice = LocalBluetoothDevice.getLocalDevice();
		remoteBluetoothDevice = localBluetoothDevice.getRemoteBluetoothDevice(address);	
		socket = remoteBluetoothDevice.openSocket(PORT);
		outputStream = socket.getOutputStream();
	}

	public void send(float[] values) throws IOException {
		StringBuilder sb = new StringBuilder();
		Formatter formatter = new Formatter(sb, new Locale("en_US.UTF8"));
		formatter.format("%+07.2f*%+07.2f*%+07.2f#", values[0], values[1], values[2]);				
		outputStream.write(sb.toString().getBytes());
	}
	
	@Override
	protected void finalize() {
		try {
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		socket.closeSocket();
	}
}
